//
//  ZCPageContentView.swift
//  ZYDY
//
//  Created by zhangchao on 2017/8/21.
//  Copyright © 2017年 zhangchao. All rights reserved.
//

import UIKit

// MARK: - 代理
protocol ZCPageContentViewDelegate : class {
    func pageContentView(contentView : ZCPageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}

// MARK: - class
class ZCPageContentView: UIView {
    
    fileprivate var childVcs : [UIViewController]
    fileprivate weak var parentVc : UIViewController?
    weak var delegate : ZCPageContentViewDelegate?
    fileprivate var startOffsetX : CGFloat = 0
    fileprivate var isScrollDelegateEnabled : Bool = true

    fileprivate lazy var collectionView : UICollectionView = {[weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.itemSize = self!.frame.size
        
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.isPagingEnabled = true
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.delegate = self
        return collectionView
    }()
    
    init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController) {
        self.childVcs = childVcs
        self.parentVc = parentViewController
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 设置UI
extension ZCPageContentView {
    
    fileprivate func setupUI() {
        
        self.backgroundColor = UIColor.yellow
        
        for childVc in childVcs {
            parentVc?.addChildViewController(childVc)
        }
        
        addSubview(collectionView)
        collectionView.frame = bounds;
        
    }
}

// MARK: - UICollectionViewDataSource
extension ZCPageContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVc = childVcs[indexPath.item]
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension ZCPageContentView : UICollectionViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isScrollDelegateEnabled = true
        startOffsetX = scrollView.contentOffset.x
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isScrollDelegateEnabled == false {
            return
        }
        
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        
        let offsetX = scrollView.contentOffset.x
        let ratio = offsetX / scrollView.bounds.width
        progress = ratio - floor(ratio)
        
        if offsetX > startOffsetX {
            // 左滑
            sourceIndex = Int(offsetX / scrollView.bounds.width)
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            if offsetX - startOffsetX == scrollView.bounds.width {
                progress = 1.0
                targetIndex = sourceIndex
            }
        } else {
            // 右滑
            targetIndex = Int(offsetX / scrollView.bounds.width)
            sourceIndex = targetIndex + 1
            if sourceIndex >= childVcs.count {
                sourceIndex = childVcs.count - 1
            }
            progress = 1 - progress
        }
        print("progress \(progress) sourceIndex \(sourceIndex) targetIndex \(targetIndex)")
        delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
    }
}

// MARK: - 对外接口
extension ZCPageContentView {
    func setCurrentIndex(currentIndex : Int) {
        isScrollDelegateEnabled = false
        let offsetX = CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
        
    }
}
